package com.hzzftech.watchdog.busi.core.task;

import com.hzzftech.watchdog.busi.constants.BusiConstant;
import com.hzzftech.watchdog.busi.domain.KtDispatcher;
import com.hzzftech.watchdog.busi.domain.KtDispatcherFailedMsg;
import com.hzzftech.watchdog.busi.mapper.KtDispatcherFailedMsgMapper;
import com.hzzftech.watchdog.busi.mapper.KtDispatcherMapper;
import com.hzzftech.watchdog.busi.module.dingding.service.DingService;
import com.hzzftech.watchdog.busi.module.email.service.IEmailService;
import com.hzzftech.watchdog.common.core.domain.entity.SysUser;
import com.hzzftech.watchdog.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.xml.ws.soap.Addressing;
import java.util.*;


@Component("WarnMsgTask")
public class WarnMsgTask {

    public static Logger logger = LoggerFactory.getLogger(WarnMsgTask.class);

//    @Value("${kt-watchdog.warn_msg_frequency}")
//    private int warn_msg_frequency;

    @Value("${kt-watchdog.warn_msg_time}")
    private long warn_msg_time;

    @Autowired
    private IEmailService emailService;

    @Autowired
    private DingService dingService;

    @Autowired
    private KtDispatcherFailedMsgMapper ktDispatcherFailedMsgMapper;

    @Autowired
    private KtDispatcherMapper dispatcherMapper;

    @Autowired
    private SysUserMapper userMapper;

    // 发送警告信息
//    @Scheduled(cron = "0 0 */1 * * ?")
    public void sendMsg() {
        logger.info("--------发送预警信息开始--------");
        KtDispatcherFailedMsg failedMsg = new KtDispatcherFailedMsg();
        failedMsg.setStatus(BusiConstant.STATUS_YES);
        failedMsg.setSendTime(warn_msg_time);
        List<KtDispatcherFailedMsg> ktDispatcherFailedMsgs = ktDispatcherFailedMsgMapper.selectKtDispatcherFailedMsgList(failedMsg);

        Map<Long, Map<Integer, Integer>> errorMap = new HashMap<>();
        Map<Long, Integer> recordLevel = new HashMap<>();
        for (KtDispatcherFailedMsg msg : ktDispatcherFailedMsgs) {
            if (msg.getEmail() != null) {
                KtDispatcher dispatcher = dispatcherMapper.selectKtDispatcherById(msg.getDpId());
                if (dispatcher != null) {
                    int warnLevel = dispatcher.getWarnLevel();
                    recordLevel.put(dispatcher.getId(), warnLevel);
                    Map<Integer, Integer> integerIntegerMap = errorMap.get(msg.getUserId());
                    if (integerIntegerMap == null) {
                        integerIntegerMap = new HashMap<>();
                        errorMap.put(msg.getUserId(), integerIntegerMap);
                    }
                    if (integerIntegerMap.get(warnLevel) == null) {
                        integerIntegerMap.put(warnLevel, 1);
                    } else {
                        integerIntegerMap.put(warnLevel, integerIntegerMap.get(warnLevel) + 1);
                    }
                }
            }

            msg.setSendTime(msg.getSendTime()+1);
            msg.setLastSendTime(new Date());
            ktDispatcherFailedMsgMapper.updateKtDispatcherFailedMsg(msg);
        }

        // 发送每个人邮箱
        for (Long userId : errorMap.keySet()) {
            SysUser user = userMapper.selectUserById(userId);
            Map<Integer, Integer> integerIntegerMap = errorMap.get(userId);

            int low = integerIntegerMap.get(1) == null ? 0 : integerIntegerMap.get(1);
            int middle = integerIntegerMap.get(2) == null ? 0 : integerIntegerMap.get(2);
            int high = integerIntegerMap.get(3) == null ? 0 : integerIntegerMap.get(3);
            int total = low + middle + high;
            String msg = "有"+total+"个任务失败，其中高等级（"+high+"个），中等级（"+middle+"个），低等级（"+low+"个）,请尽快登录系统查看解决！";
            emailService.sendAttachMail(user.getEmail(), BusiConstant.CONTACT_HEADER_MSG, msg);
        }

        if (recordLevel.size() > 0) {
            int high = 0, middle = 0, low = 0;
            Set<Map.Entry<Long, Integer>> entries = recordLevel.entrySet();
            for (Map.Entry<Long, Integer> entry : entries) {
                Integer value = entry.getValue();
                if (value == 1) {
                    low ++;
                } else if (value == 2) {
                    middle ++;
                } else if (value == 3) {
                    high ++;
                }
            }
            String msg = "有"+recordLevel.size()+"个任务失败，其中高等级（"+high+"个），中等级（"+middle+"个），低等级（"+low+"个）,请尽快登录系统查看解决！";
            dingService.sendDingTalk(msg);
        }

        logger.info("--------发送预警信息结束--------");
    }
}
